package net.ojbk.twobox;


import net.ojbk.twobox.pojo.TcpMessage;
import org.junit.Test;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * PACKAGE_NAME: Main.tcp
 * Description:
 */
public class TCPTest5 {
    @Test
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        int localPort = -1;
        for (int i = 0; i < 50; i++) {
            Thread.sleep(1000);
            Socket socket = new Socket();
            socket.setReuseAddress(true);
            if (localPort != -1)
                socket.bind(new InetSocketAddress(localPort));
            if (i >= 1)
                socket.connect(new InetSocketAddress("ojbk.net", 9999));
            else
                socket.connect(new InetSocketAddress("sso.ojbk.net", 9999));
            localPort = socket.getLocalPort();
            System.out.println("建立链接,目标地址：" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + "。本地地址：" + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort());
            //int localPort = socket.getLocalPort();
            SocketAddress sdasa = socket.getLocalSocketAddress();
            TcpMessage tcpMessage = new TcpMessage();
            tcpMessage.code = 5;
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
            objectOutputStream.writeObject(tcpMessage);
            objectOutputStream.flush();
            // 接收
            TcpMessage responseMsg = (TcpMessage) objectInputStream.readObject();
            Object[] data = (Object[]) responseMsg.data;
            String ip = (String) data[0];
            int port = (int) data[1];
            System.out.println("外网地址：" + ip + ":" + port);
            // 发送关闭请求
            TcpMessage tcpMessage1 = new TcpMessage();
            tcpMessage.code = 5;
            objectOutputStream.writeObject(tcpMessage1);
            objectOutputStream.flush();

            // 断开
            objectInputStream.close();
            objectOutputStream.close();
            socket.close();
            System.out.println("断开第" + i + "此链接");
        }
    }
}
